import { billListApi, confirmedBillListApi } from '@/api/pcs/pcsBillManage'
import { defaultPageSize } from '@/utils/antdHelper'
import { formatDate } from '@/utils/displayHelper'
import modelExtend from '@/utils/dvaUtil/modelExtend'
import { PCS_BILL_MANAGE_TAB_ENUM } from '@/utils/enum'

export const namespace = 'pcsBillManage'

const initialState = {
  activeKey: PCS_BILL_MANAGE_TAB_ENUM.WAIT_CONFIRM,
  searchParams: {},
  pagination: {
    current: 1,
    pageSize: defaultPageSize,
    total: 0,
  },
  pageList: [],
}

export default modelExtend({
  namespace,
  state: initialState,
  matchedActions: toAction => {
    toAction('getPageList')
  },
  effects: {
    *getPageList({ payload }, { toAction, select }) {
      const { activeKey } = yield select(state => state[namespace])
      if (activeKey === PCS_BILL_MANAGE_TAB_ENUM.WAIT_CONFIRM) {
        yield toAction('getBillList', payload)
      } else {
        yield toAction('getConfirmedPageList', payload)
      }
    },
    *getBillList({ payload }, { call, update, select }) {
      const { searchParams } = yield select(state => state[namespace])
      const params = {
        ...searchParams,
        ...payload,
      }
      if (params.orderCreateDate?.length) {
        params.orderCreateStartDate = formatDate(params.orderCreateDate[0])
        params.orderCreateEndDate = formatDate(params.orderCreateDate[1])
        delete params.orderCreateDate
      }
      if (params.serviceDate?.length) {
        params.serviceStartDate = formatDate(params.serviceDate[0])
        params.serviceEndDate = formatDate(params.serviceDate[1])
        delete params.serviceDate
      }

      const { data } = yield call(billListApi, params)
      yield update({
        pageList: data,
      })
    },
    *getConfirmedPageList({ payload }, { call, update, select }) {
      const { searchParams, pagination } = yield select(state => state[namespace])
      const params = {
        ...searchParams,
        ...pagination,
        ...payload,
      }
      if (params.orderCreateDate?.length) {
        params.orderCreateStartDate = formatDate(params.orderCreateDate[0])
        params.orderCreateEndDate = formatDate(params.orderCreateDate[1])
        delete params.orderCreateDate
      }
      if (params.serviceDate?.length) {
        params.serviceStartDate = formatDate(params.serviceStartDate[0])
        params.serviceEndDate = formatDate(params.serviceEndDate[1])
        delete params.serviceDate
      }

      const { data } = yield call(confirmedBillListApi, params)
      const { content, current, pageSize, total, totalCount, totalBillAmount, totalNursingAmount, totalServiceCharge } =
        data
      yield update({
        pageList: content,
        pagination: { current, pageSize, total },
        totalCount,
        totalBillAmount,
        totalNursingAmount,
        totalServiceCharge,
      })
    },
  },
})
